package com.glamour.hlcity.web.action;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;



import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;



import com.glamour.hlcity.common.model.Attachment;
import com.glamour.hlcity.common.model.Entity;
import com.glamour.hlcity.common.util.MapUtil;
import com.glamour.hlcity.common.util.StringUtil;
import com.glamour.hlcity.component.upload.util.FileUtil;

import com.glamour.hlcity.web.BaseObject;


/**
 * 文件上传
 * 
 * @author zhaoxing.liuzx
 * 
 */
public class UploadAction  extends BaseObject {
	private final static String FILE_TYPE_DEFAULT="unKnow";
	private File fileupload;// 获取上传文件
	private String fileuploadFileName;// 获取上传文件名称
	private final static Log LOG=LogFactory.getLog(UploadAction.class);

	public File getFileupload() {
		return fileupload;
	}

	public void setFileupload(File fileupload) {
		this.fileupload = fileupload;
	}

	public String getFileuploadFileName() {
		
		return fileuploadFileName;
	}

	public void setFileuploadFileName(String fileuploadFileName) {
		this.fileuploadFileName = fileuploadFileName;
	}

	public String upload()  {
			
		try {
			
			/**
			 * step1:保存文件,组装成attachment
			 */
			//附件相对目录路径
			String fileDir=FileUtil.createDir();
			String path=path();
			//附件绝对目录路径
			String relativeDir=path+fileDir;
			//创建绝对目录
			FileUtil.mkdir(relativeDir);
			Attachment attachment =attachment();
			//文件名称
			String newFileName=attachment.getName()+"."+attachment.getType();
			
			File newFile=new File(relativeDir+newFileName);
			
			FileUtil.copyFile(fileupload, newFile);
			attachment.setRelativePath(relativeDir+newFileName);
			attachment.setAbsolutePath(fileDir+newFileName);
			attachment.setSize(new BigDecimal(FileUtil.size(newFile)));
			//step3:返回数据
			String data=MapUtil.toMap(attachment).toString();
			System.out.print(data);
			return SUCCESS;
			
		} catch (IOException e) {
			
			LOG.error("文件上传失败",e);
			return FAIL;
		} 
	
		
	

	}

	/**
	 * 组装成附件实例
	 * @return
	 */
	private Attachment attachment(){
		Attachment attachment=new Attachment();
		attachment.setCreator(Entity.USER_ADMIN);
		attachment.setDeleted(Entity.DELETED_1);
		attachment.setModifier(Entity.USER_ADMIN);
		attachment.setOrignName(fileuploadFileName);
		attachment.setType(StringUtil.suffix(fileuploadFileName, FILE_TYPE_DEFAULT));
		return attachment;
	}
	

}
